//
//  MSLNewsMainTableView.m
//  MSLNews
//
//  Created by lirenqiang on 16/6/12.
//  Copyright © 2016年 lirenqiang. All rights reserved.
//

#import "MSLNewsMainTableView.h"
#import "MSLChannelModel.h"
#import "MSLNewsModel.h"
#import "MSLNewsTableViewCell.h"
#import "MSLNetworking.h"


@interface MSLNewsMainTableView () <UITableViewDataSource>

@end

@implementation MSLNewsMainTableView {
    NSMutableArray <MSLNewsModel *> * _newsModel;
    
    UIActivityIndicatorView * _indicatorView;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        self.dataSource = self;
        
        UINib * nib = [UINib nibWithNibName:@"MSLNewsTableViewCell" bundle:nil];
        [self registerNib:nib forCellReuseIdentifier:MSLNewsTableViewCellId];
        
        self.rowHeight = 100;
        
        _indicatorView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
       
        dispatch_async(dispatch_get_main_queue(), ^{
             _indicatorView.center = self.center;
        });
        
        _indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        
        [self addSubview:_indicatorView];
        
    }
    return self;
}


#pragma mark - data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _newsModel.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MSLNewsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:MSLNewsTableViewCellId forIndexPath:indexPath];

    
    cell.newsModel = _newsModel[indexPath.item];
    
    return cell;
    
}



#pragma mark - lazy load
- (void)setChannelModel:(MSLChannelModel *)channelModel {
    _channelModel = channelModel;
    
    [_newsModel removeAllObjects];
    
    [self reloadData];
    
    [_indicatorView startAnimating];
    
    [self loadData];
    
    
}

#pragma mark - 加载网络数据
- (void)loadData {
 
    [[MSLNetworking sharedNetworking] loadTableViewData:_channelModel.tid finished:^(id responseObject, NSError *error) {
        if (error) {
            NSLog(@"error: %@", error);
            return;
        }
        
        NSLog(@"%@", responseObject);
        NSArray * arrDict = responseObject[_channelModel.tid];
        
        _newsModel = [NSMutableArray arrayWithCapacity:arrDict.count];
        
        for (NSDictionary * dict in arrDict) {
            [_newsModel addObject:[MSLNewsModel newsModelWithDict:dict]];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self reloadData]; 
            
            [_indicatorView stopAnimating];
        });
    }];
}




@end
